﻿using System;
using System.IO;
using System.Text;

namespace TDM.WebBase
{
    /// <summary>
    /// 调试用日志管理
    /// </summary>
    public class LogHelper
    {
        private static readonly object _lockObj = new object();

        private static string DebugLogFile = "debug.log";

        private static string InfoLogFile = "info.log";

        private static string ErrLogFile = "error.log";

        private static string LogPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");

        /// <summary>
        /// 写入调试日志
        /// </summary>
        public static void Debug(string message) => WriterLog(message, LogLevel.Debug);

        /// <summary>
        /// 写入信息日志
        /// </summary>
        public static void Info(string message) => WriterLog(message, LogLevel.Info);

        /// <summary>
        /// 写入错误日志
        /// </summary>
        public static void Error(string message) => WriterLog(message, LogLevel.Error);
        /// <summary>
        /// 写入错误日志
        /// </summary>
        public static void Error(Exception ex) => WriterLog(ex.ToString(), LogLevel.Error);

        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="level"></param>
        public static void WriterLog(String message, LogLevel level)
        {
            string logFile = "";
            switch (level)
            {
                case LogLevel.Debug:
                    logFile = Path.Combine(LogPath, DebugLogFile);
                    break;
                case LogLevel.Info:
                    logFile = Path.Combine(LogPath, InfoLogFile);
                    break;
                case LogLevel.Error:
                    logFile = Path.Combine(LogPath, ErrLogFile);
                    break;
            }
            if (!Directory.Exists(LogPath))
            {
                Directory.CreateDirectory(LogPath);
            }
            // 构建日志内容
            string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {message}{Environment.NewLine}";

            // 线程安全的写入操作
            lock (_lockObj)
            {
                // 使用追加模式写入，自动处理文件创建
                File.AppendAllText(logFile, logEntry, Encoding.UTF8);
            }
        }
    }

    /// <summary>
    /// 日志类型
    /// </summary>
    public enum LogLevel
    {
        Debug,
        Info,
        Error
    }
}
